package com.topway.dsmflex.thread.services;

import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.topway.dsmflex.model.synchro.DataTableBean;


/**
 * 
 * @author liusy 2013-05-2
 *
 */
public class SynchroServices {

	private static Logger log = Logger.getLogger(SynchroServices.class);
	
	
	private static ThreadLocal<SynchroServices> synchroServices= new ThreadLocal<SynchroServices>();
	
	private DbSynchroServices synchroDao = null;
	
	public SynchroServices()
	{
		this.synchroDao = new DbSynchroServices();
	}
	
	public synchronized static SynchroServices getSynchroServices()
	{
		if(null==synchroServices.get())
		{
			synchroServices.set(new SynchroServices());
		}
		return synchroServices.get();
	}
	
	private int OperatorSource(DataTableBean dt)
	{
		int result=0;
		try {
			if(null!=dt.getDeleteSourceSql()&&!dt.getDeleteSourceSql().equals("")&&null!=dt.getOperatorSource()&&dt.getOperatorSource().equals("DELETE"))
				result=  synchroDao.updateTableState( dt.getSourceDataSource(),dt.getDeleteSourceSql());
			  else if(null!=dt.getUpdateSourceSql()&&!dt.getUpdateSourceSql().equals("")&&null!=dt.getOperatorSource()&&dt.getOperatorSource().equals("UPDATE"))
				  result=  synchroDao.updateTableState( dt.getSourceDataSource(),dt.getUpdateSourceSql());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	private int OperatorTarget(DataTableBean dt)
	{
		int result=0;
		try {
			result=  synchroDao.updateTableState(dt.getTargetDataSource(),dt.getTargetExecuteSql());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public int synchroInsertData(DataTableBean dt) throws SQLException {
		int result = 0;
		result = synchroDao.synchroInsertData( dt);
		if (result > 0)
		{
			OperatorSource(dt);
			if(null!=dt.getTargetExecuteSql()&&!dt.getTargetExecuteSql().equals(""))
				OperatorTarget(dt);
		}
		return result;
	}

	public int synchroUpdateData( DataTableBean dt) throws SQLException {
		int result = 0;
		result = synchroDao.synchroUpdateData(dt);
		if (result > 0)
		{
			OperatorSource(dt);
			if(null!=dt.getTargetExecuteSql()&&!dt.getTargetExecuteSql().equals(""))
				OperatorTarget(dt);
		}
		return result;
	}
		  
	public int synchroInsertOrUpdateData(DataTableBean dt) throws SQLException {
		int result = 0;
		result = synchroDao.synchroInsertOrUpdateData( dt);
		if (result > 0)
		{
			OperatorSource(dt);
			if(null!=dt.getTargetExecuteSql()&&!dt.getTargetExecuteSql().equals(""))
				OperatorTarget(dt);
		}
		return result;
	}
	
	
	public int synchroDeleteData(DataTableBean dt) throws SQLException {
		int result = 0;
		result = synchroDao.synchroDeleteData( dt);
		if (result > 0)
		{
			OperatorSource(dt);
			if(null!=dt.getTargetExecuteSql()&&!dt.getTargetExecuteSql().equals(""))
				OperatorTarget(dt);
		}
		return result;
	}
	
	
	
	   public static void main(String[] args) {
		String str = "a,";
			String [] a = str.split(",");
			System.out.println(a.length);
	}
     
}
